import BackPage from '@/components/BackPage';
import Conversation from '@/components/Conversation';
import SelectOne from '@/components/SelectOne';
import { getReviewedList } from '@/services/business';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Image } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useRef, useState } from 'react';
import styles from './index.less';

const Sales: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const colorThem = localStorage.getItem('color') || '#1a7721';
  const [list, setList] = useState<any[]>([]);
  const [selectList, setSelectList] = useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [conversation, setConversation] = useState<boolean>(false);
  const [business, setBusiness] = useState({ id: '', userId: '' });
  const [imgsClick, setImgsClick] = useState<any[]>([]);

  const getList = useCallback(async () => {
    try {
      const res = await getReviewedList({ pageIndex: currentPage, pageSize: 4 });
      setTotal(res.total);
      setList(res.list);
      let arr: any[] = [];
      res.list.map((item: any) => {
        arr.push({ id: item.id, visible: false });
      });
      setImgsClick(arr);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage]);

  useEffect(() => {
    getList();
  }, [getList]);

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '商家编号',
      dataIndex: 'userId',
      width: 150,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '注册人',
      dataIndex: 'nickname',
      width: 110,
      ellipsis: true,
    },
    {
      title: '店铺名称',
      width: 150,
      dataIndex: 'saleName',
      ellipsis: true,
    },
    {
      title: '手机号',
      width: 150,
      dataIndex: 'tel',
      ellipsis: true,
    },
    {
      title: '地址',
      dataIndex: 'address',
      width: 180,
      ellipsis: true,
      render: (_, record) => {
        return (
          <span
            key={record.id}
          >{`${record.province} ${record.city} ${record.area} ${record.addressDetail}`}</span>
        );
      },
    },
    {
      title: '营业执照',
      width: 220,
      align: 'center',
      dataIndex: 'certificate',
      render: (_, record) => {
        return (
          <Image
            src={`http://localhost:8090/dyh/upload_images/business/${record.certificate}`}
            alt={'加载失败'}
            key={record.id}
            width={130}
          />
        );
      },
    },
    {
      title: '店铺logo',
      width: 220,
      dataIndex: 'saleLogo',
      align: 'center',
      render: (_, record) => {
        return (
          <Image
            src={`http://localhost:8090/dyh/upload_images/business/${record.saleLogo}`}
            alt={'加载失败'}
            key={record.id}
            width={130}
          />
        );
      },
    },
    {
      title: '内景照片',
      width: 220,
      align: 'center',
      key: 'imgs',
      render: (_, record) => {
        let current = JSON.stringify(record.intoPicture)
          .replace('[', '')
          .replace(']', '')
          .replace(/"/g, '')
          .replace(/\\/g, '')
          .split(',');

        return (
          <div className={styles.imgController} key={record.id}>
            {imgsClick.map((item, index: number) => {
              if (item.id === record.id) {
                return (
                  <div key={record.id}>
                    <Image
                      preview={{ visible: false }}
                      width={130}
                      src={`http://localhost:8090/dyh/upload_images/business/${current[0]}`}
                      onClick={() => {
                        let arr: any[] = imgsClick;
                        arr.splice(index, 1, { id: item.id, visible: true });
                        setImgsClick(JSON.parse(JSON.stringify(arr)));
                      }}
                      className={styles.goodsImgs}
                    />
                    <div style={{ display: 'none' }}>
                      <Image.PreviewGroup
                        preview={{
                          visible: item.visible,
                          onVisibleChange: (vis) => {
                            let arr: any[] = imgsClick;
                            arr.splice(index, 1, { id: item.id, visible: vis });
                            setImgsClick(JSON.parse(JSON.stringify(arr)));
                          },
                        }}
                      >
                        {current.map((items) => (
                          <Image
                            key={items}
                            width={500}
                            src={`http://localhost:8090/dyh/upload_images/business/${items}`}
                          />
                        ))}
                      </Image.PreviewGroup>
                    </div>
                  </div>
                );
              } else {
                return;
              }
            })}
          </div>
        );
      },
    },
    {
      title: '注册时间',
      key: 'timeAdd',
      width: 150,
      render: (text, record) => [
        <div key={record.id}>{`${moment(Number(record.timeAdd)).format(
          'YYYY-MM-DD HH:mm:ss',
        )}`}</div>,
      ],
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 100,
      fixed: 'right',
      align: 'center',
      render: (text, record) => [
        <div
          key={record.id}
          className={styles.delete}
          onClick={() => {
            setBusiness(record);
            setConversation(true);
          }}
          style={{ border: `1px solid ${colorThem}`, color: colorThem }}
        >
          联系商家
        </div>,
      ],
    },
  ];

  return (
    <BackPage thisRoute={'/sales'} lastRoute={'商家管理'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'卖家编号'}
          fromWhere={'sale'}
          selected={(value) => {
            setSelectList(value);
          }}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          actionRef={actionRef}
          scroll={{ x: 1230 }}
          cardBordered={false}
          dataSource={selectList.length !== 0 ? selectList : list}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={false}
          options={false}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 4, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
        {conversation && (
          <Conversation
            receiveId={business.userId}
            color={colorThem}
            business={business}
            visible={conversation}
            onCancel={() => {
              setConversation(false);
            }}
          />
        )}
      </div>
    </BackPage>
  );
};
export default Sales;
